import { ref } from 'vue';
import { defineStore } from 'pinia';
import { ElLoading, ElMessage } from 'element-plus';
import api from '@/http/api';
import router from '@/router/index';
import { useRouterStore } from '@/pinia/modules/router';

export const useUserStore = defineStore('user', () => {
  const loadingInstance = ref(null);

  const userInfo = ref({
    id: '',
    name: '',
    organizations: [],
  });

  const setToken = (val) => {
    window.localStorage.setItem('token', val);
  };

  const getToken = () => {
    return window.localStorage.getItem('token') || '';
  };

  const setUser = (val) => {
    userInfo.value = val;
  };

  const getUser = () => {
    return userInfo.value;
  };

  const initUserInfo = async() => {
    const res = await api.post('/loginInfo');
    if (res.code === "1") {
      setUser(res.data);
      return res;
    } else {
      setToken(null);
      throw new Error('用户信息获取失败！');
    }
  };

  const login = async(loginInfo) => {
    loadingInstance.value = ElLoading.service({
      fullscreen: true,
      text: '登录中，请稍候...',
    });
    try {
      const res = await api.login(loginInfo);
      if (res.code === "1") {
        setUser(res.data);
        setToken(res.data.token);
        const routerStore = useRouterStore();
        await routerStore.initRouter(router);
        await router.push({ name: 'trade' });
        loadingInstance.value.close();
        return true;
      }
    } catch (e) {
      console.log(e);
      loadingInstance.value.close();
    }
    loadingInstance.value.close();
  };

  const logout = async() => {
    api.logout().then(async(res) => {
      ElMessage.success(res.message);
      clearStorage();
      await router.push({name: 'login', replace: true});
      window.location.reload();
    })
  };

  const clearStorage = () => {
    window.localStorage.clear();
    window.sessionStorage.clear();
  };

  return {
    setUser,
    getUser,
    setToken,
    getToken,
    login,
    logout,
    initUserInfo,
    loadingInstance,
    clearStorage
  };
});
